package com.carpedil.smvc.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/** @author Administrator */
@Controller
public class FileDownLoadController {
  @RequestMapping("/download")
  public String downLoad(
      String filename, HttpServletRequest request, HttpServletResponse response) {
    // 获取文件真实物理地址
    String realPath = request.getServletContext().getRealPath("files");
    System.out.println("realPath = " + realPath);
    // 规定消息头
    response.setHeader("Content-Disposition", "attachment;filename=" + filename);
    // 获取下载文件对象
    File imgFile = new File(realPath, filename);
    ServletOutputStream out = null;
    try {
      // 将下载文件对象转为byte类型数据数组
      byte[] bytes = FileUtils.readFileToByteArray(imgFile);
      // 获取输出流
      out = response.getOutputStream();
      // 将byte数组数据通过输出流输出
      out.write(bytes);
      // 刷新管道
      out.flush();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (out != null) {
        try {
          // 关闭流
          out.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return "redirect:/do.jsp";
  }
}
